package com.ruoyi.handler;


import com.ruoyi.domain.common.ResponseResult;
import com.ruoyi.exception.BaseException;
import com.ruoyi.exception.TokenExpiredException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;


/**
 * @Author: lsx
 * @Description:  全局异常处理器
 * @Create:  2025/1/7 9:19
 **/
@RestControllerAdvice()
public class GlobalExceptionHandler {


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult handleValidationExceptions(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getFieldErrors().forEach(error ->
                errors.put(error.getField(), error.getDefaultMessage()));
        return ResponseResult.error(errors.toString());
    }

    @ExceptionHandler(TokenExpiredException.class)
    public ResponseResult BaseHandler(TokenExpiredException exception){
        return ResponseResult.tokenError(exception.getMessage());
    }

    @ExceptionHandler(BaseException.class)
    public ResponseResult BaseHandler(BaseException exception){
        return ResponseResult.error(exception.getMessage());
    }
}